<?php

use \GatewayWorker\Lib\Gateway;
//有意义协议
class cmd_reconnect extends cmdbase
{
	public function onCmd($msg){
		//组装玩家id
		$user_id = ClientMgr::getUid($msg->user, $msg->psw);
		$_SESSION[SessionTag::uid] = $user_id;
 		//把在线的旧玩家踢下线
		if(Gateway::isUidOnline($user_id)){
			$client_id_list = Gateway::getClientIdByUid($user_id);
			foreach ($client_id_list as $client_id) {
				$notify_kick = new notify_kick();
				$notify_kick->msg = "reconnect kick out";
				$message = Events::wrapMsg(notify_kick::class, $notify_kick);
				Gateway::closeClient($client_id, $message);
				echo "warning=>玩家在线，需要提下线:$client_id\n";
			}
		}

		$client_id = $this->getCurClientId();
		//绑定用户id，方便下次踢人或者恢复现场
 		Gateway::bindUid($client_id, $user_id);

		$msg_body = new reconnect_rsp();
		$msg_body->ret = NetErrorCode::None;
		$msg_body->reason = $user_id;


		if($msg->group_id == ""){
			echo "不在房间里的重连\n";
			return $msg_body;
		}
 		//如果还在房间，加入房间
		$group_mgr = $GLOBALS['GroupMgr']; 
		$group_id = $group_mgr->getActiveGroupId($msg->group_id);
		if(isset($group_id)){
			echo "加入旧组：$group_id\n";

			//广播
			$member_info = new member_info();
			$member_info->uid = $user_id;
			$member_info->name = ClientMgr::getNameByUid($user_id);
			//跨服数据读取
			$group_mgr->writeMemberInfo($member_info, $group_id);

			$notify_enterroom = new notify_enterroom();
			$notify_enterroom->member = $member_info;
			Events::sendToGroup($group_id, notify_enterroom::class, $notify_enterroom);

			//加入组
			$group_mgr->joinGroup($group_id);

			//返回消息
			$notify_sycroom = new notify_sycroom();
			$member_infos = array();
			$uid_list = Gateway::getUidListByGroup($group_id);
			foreach ($uid_list as $uid) {
				$member_info = new member_info();
				$member_info->uid = $uid;
				$member_info->name = ClientMgr::getNameByUid($uid);
				//跨服数据读取
				$group_mgr->writeMemberInfo($member_info, $group_id);
				$member_infos[] = $member_info;
			}
			$notify_sycroom->member_infos = $member_infos;
			$this->sendToCurrentClient(notify_sycroom::class, $notify_sycroom);
		}else{
			echo "不加入旧组：$group_id 因为不存在了\n";
		}

 		return $msg_body;
	}
}